#include "test.h"
#include <QMouseEvent>
#include <QCursor>
#include <QDebug>

#include "test2.h"
CustomPlotWidget::CustomPlotWidget(QWidget *parent) : QCustomPlot(parent), pixmapItem(nullptr) {
    setInteractions(QCP::iRangeDrag | QCP::iRangeZoom);
    setSelectionRectMode(QCP::srmZoom);
}

void CustomPlotWidget::SetupPixmapItem(QPixmap &pixmap)
{
    // 创建并配置QCPItemPixmap
    pixmapItem = new QCPItemPixmap(this);
    pixmapItem->setPixmap(pixmap);

    ///加载图片并设置区域到框选区域右上角
    double width = mRectItem->bottomRight->key() - mRectItem->topLeft->key();// 框选区域宽
    double height = abs(mRectItem->topLeft->value() - mRectItem->bottomRight->value());// 框选区域高
    //qDebug() << "pixmap:" << width << height << mRectItem->topLeft->value() << mRectItem->bottomRight->value();
    pixmapItem->topLeft->setType(QCPItemPosition::ptAbsolute);
    pixmapItem->topLeft->setPixelPosition(QPointF(1200, 300));
    pixmapItem->bottomRight->setType(QCPItemPosition::ptAbsolute);
    pixmapItem->bottomRight->setPixelPosition(QPointF(1600, 500));
//    pixmapItem->topLeft->setCoords(mRectItem->bottomRight->key() + (width * 0.2), mRectItem->topLeft->value() + height);
//    pixmapItem->bottomRight->setCoords(mRectItem->bottomRight->key() + (width * 0.2) + width, mRectItem->topLeft->value());
    ///启用缩放并设置边框
    pixmapItem->setScaled(true, Qt::KeepAspectRatio);

    //添加关联线
    DynamicPixmapBinder *binder = new DynamicPixmapBinder(this);
    binder->addConnection(mRectItem, pixmapItem);
    // 刷新图表
    this->replot();
}

void CustomPlotWidget::mousePressEvent(QMouseEvent *event) {
    ///框选放大
    if (event->button() == Qt::LeftButton)
    {
        // 创建虚线选框图形项
        if (!mRectItem) {
            mIsSelecting = true;
            mStartPos = event->pos(); // 记录起始像素位置
            mRectItem = new QCPItemRect(this);
            mRectItem->setPen(QPen(Qt::black, 1, Qt::DashLine));
            mRectItem->setBrush(Qt::NoBrush);
        }
        mRectItem->setVisible(true);
    }

    /// 检测pixmapItem选中状态
    if(pixmapItem)
    {   // 检测是否点击到图片项（阈值8像素）
        double dist = pixmapItem->selectTest(event->pos(), false);
        qDebug() << "dist:" << dist;
        if(dist >= 0 && dist < 8)
        {
            pixmapItem->setSelected(true);
            pixmapItem->setPen(QPen(Qt::red));
//            QPointF pos = this->mapToViewport(event->pos());
//            double x = xAxis->pixelToCoord(event->pos().x());
//            double y = yAxis->pixelToCoord(event->pos().y());
//            QPointF pos = QPointF(x, y);
            QPointF pos = event->pos();
            // 记录初始状态
            m_dragStartPos = pos;
            m_originalTopLeft = pixmapItem->topLeft->pixelPosition();
            m_originalBottomRight = pixmapItem->bottomRight->pixelPosition();
//            m_originalTopLeft = pixmapItem->topLeft->coords();
//            m_originalBottomRight = pixmapItem->bottomRight->coords();


            // 检测是否在缩放角落（右下角）
            QPointF p1 = pixmapItem->topLeft->pixelPosition();
            QPointF p2 = pixmapItem->bottomRight->pixelPosition();
//            QPointF p1 = pixmapItem->topLeft->coords();
//            QPointF p2 = pixmapItem->bottomRight->coords();
//            qDebug() << p1.x() << p1.y();
//            QRectF rect = pixmapItem->getFinalRect();
            QRectF rect(p1, p2);
            QRectF cornerArea(rect.bottomRight() - QPointF(8,48), QSizeF(16,16));
            qDebug() << rect.bottomRight() << cornerArea.x() << cornerArea.y() << pos;
            m_resizing = cornerArea.contains(pos);
            m_dragging = !m_resizing;
            qDebug() << "test:" << m_resizing << m_dragging;
        }else
        {
            pixmapItem->setSelected(false);
            pixmapItem->setPen(QPen(Qt::red));
        }
    }

    ///移动图片
    if(event->button() == Qt::RightButton){
        // 将鼠标位置转换为轴坐标
//        double x = xAxis->pixelToCoord(event->pos().x());
//        double y = yAxis->pixelToCoord(event->pos().y());
//        QPointF pos = QPointF(x, y);
        QPointF pos = event->pos();
        //qDebug() << pixmapItem->selectTest(event->pos(), false);
        if (pixmapItem && pixmapItem->selectTest(event->pos(), false) < 8) {
            qDebug() << "点击到图";
            mDragging = true;
            mCurrentPixmap = pixmapItem;
            mDragStartPos = pos;
//            mOriginalTopLeft = pixmapItem->topLeft->coords();
//            mOriginalBottomRight = pixmapItem->bottomRight->coords();
            mOriginalTopLeft = pixmapItem->topLeft->pixelPosition();
            mOriginalBottomRight = pixmapItem->bottomRight->pixelPosition();
            qDebug() << "点击到图item";
        }
    }

    QCustomPlot::mousePressEvent(event);
}

void CustomPlotWidget::mouseMoveEvent(QMouseEvent *event) {
    QString pos = QString("%1,%2").arg(event->pos().x()).arg(event->pos().y());
    QToolTip::showText(event->globalPos(), pos, this);
    ///框选放大
    if (mIsSelecting && mRectItem) {
            // 更新选框的右下角坐标
            QPointF currentPos = event->pos();
            QRectF rect = QRectF(mStartPos, currentPos).normalized();

            // 将像素坐标转换为轴坐标
            QCPRange xRange(xAxis->pixelToCoord(rect.left()), xAxis->pixelToCoord(rect.right()));
            QCPRange yRange(yAxis->pixelToCoord(rect.top()), yAxis->pixelToCoord(rect.bottom()));

            // 设置选框位置
            mRectItem->topLeft->setCoords(xRange.lower, yRange.upper);
            mRectItem->bottomRight->setCoords(xRange.upper, yRange.lower);

            replot();
    }

    ///移动图片
    if (pixmapItem && mDragging && mCurrentPixmap) {
        // 计算当前鼠标位置对应的坐标
//        double x = xAxis->pixelToCoord(event->pos().x());
//        double y = yAxis->pixelToCoord(event->pos().y());
        double x = event->pos().x();
        double y = event->pos().y();
        QPointF delta(x - mDragStartPos.x(), y - mDragStartPos.y());
        // 更新图片位置（保持尺寸不变）
        QPointF newTopLeft = mOriginalTopLeft + delta;
        QPointF newBottomRight = mOriginalBottomRight + delta;
//        mCurrentPixmap->topLeft->setCoords(newTopLeft);
//        mCurrentPixmap->bottomRight->setCoords(newBottomRight);
        mCurrentPixmap->topLeft->setType(QCPItemPosition::ptAbsolute);
        mCurrentPixmap->topLeft->setPixelPosition(newTopLeft);
        mCurrentPixmap->bottomRight->setType(QCPItemPosition::ptAbsolute);
        mCurrentPixmap->bottomRight->setPixelPosition(newBottomRight);
        replot();
    }

    if(pixmapItem)
    {
//        QPointF pos = this->mapToViewport(event->pos());
        QPointF pos = event->pos();
        QPointF delta = pos - m_dragStartPos;
//        double x = xAxis->pixelToCoord(event->pos().x());
//        double y = yAxis->pixelToCoord(event->pos().y());
//        QPointF delta(x - m_dragStartPos.x(), y - m_dragStartPos.y());
        if (m_dragging) {
            // 拖拽移动整个Pixmap
//            pixmapItem->topLeft->setCoords(m_originalTopLeft + delta);
//            pixmapItem->bottomRight->setCoords(m_originalBottomRight + delta);
            pixmapItem->topLeft->setType(QCPItemPosition::ptAbsolute);
            pixmapItem->topLeft->setPixelPosition(m_originalTopLeft + delta);
            pixmapItem->bottomRight->setType(QCPItemPosition::ptAbsolute);
            pixmapItem->bottomRight->setPixelPosition(m_originalBottomRight + delta);
        }
        else if (m_resizing)
        {
            // 拖拽右下角缩放
//            pixmapItem->bottomRight->setCoords(m_originalBottomRight + delta);
            pixmapItem->bottomRight->setType(QCPItemPosition::ptAbsolute);
            pixmapItem->bottomRight->setPixelPosition(m_originalBottomRight + delta);
        }
        replot();
    }
}

void CustomPlotWidget::mouseReleaseEvent(QMouseEvent *event) {
    ///移动图片
    if (pixmapItem && event->button() == Qt::RightButton && mDragging) {
        mDragging = false;
        mCurrentPixmap = nullptr;
    }

    if (pixmapItem)
    {
        m_dragging = false;
        m_resizing = false;
    }

    ///框选放大
    if (event->button() == Qt::LeftButton && mIsSelecting) {
        mIsSelecting = false;

        // 获取最终选框的轴坐标范围
        QRectF rect = QRectF(mStartPos, event->pos()).normalized();
        QCPRange xRange(xAxis->pixelToCoord(rect.left()), xAxis->pixelToCoord(rect.right()));
        QCPRange yRange(yAxis->pixelToCoord(rect.top()), yAxis->pixelToCoord(rect.bottom()));

        // 隐藏选框
        // mRectItem->setVisible(false);

        // 调整坐标轴范围以放大到选中区域
        xAxis->setRange(xRange);
        yAxis->setRange(yRange);
        replot();
    }

    QCustomPlot::mouseReleaseEvent(event);
}



